package common.splitpage;


public class PageImpl implements Pageable {
	protected PageInfo pageInfo;

	protected Condition condition;

	protected int startRow;
	protected int endRow;

	public PageImpl(PageInfo pageInfo) {
		this.pageInfo = pageInfo;
		this.condition = pageInfo.getCondition();
	}

	private int getPageCount() {
		int rowCount = condition.getRowCount();
		int pageSize = condition.getPageSize();
		if (rowCount == 0) {
			return 0;
		}
		if (pageSize == 0) {
			condition.setPageSize(rowCount);
			return 1;
		}
		// calculate PageCount
		double doublePages = (double) rowCount / pageSize;
		int intPages = (int) doublePages;
		if (doublePages > intPages) { 
			intPages += 1;
		}
		return intPages;
	}


	private int getPageRowCount() {
		int rowCount = condition.getRowCount();
		int pageSize = condition.getPageSize();
		int curPage = condition.getCurPage();
		if (rowCount == 0) {
			return 0;
		}
		if (curPage != getPageCount()) {
			return pageSize;
		}
		// 
		return rowCount - (this.getPageCount() - 1) * pageSize;
	}

	// 
	private void setPageRows() {
		int rowCount = condition.getRowCount();
		int pageSize = condition.getPageSize();
		int page = condition.getCurPage();
		int pageCount = this.getPageCount();
		if (page < 1) {
			page = 1;
		}
		if (page > pageCount) {
			page = pageCount;
		}

		int startRow = (page - 1) * pageSize + 1;
		if(startRow < 0) startRow = 0;
		int endRow = startRow + pageSize - 1;
		if (page == pageCount) {
			endRow = rowCount;
		}
		condition.setCurPage(page);
		if (page == 1)
			condition.setFirst(true);
		if (page == pageCount)
			condition.setLast(true);
		if (page < pageCount)
			condition.setHasNext(true);
		if (page > 1)
			condition.setHasPrevious(true);

		this.startRow = startRow;
		this.endRow = endRow;
		condition.setStartRow(startRow);
		condition.setEndRow(endRow);
	}

	private void pageFirst() {
		condition.setCurPage(1);
	}

	private void pageLast() {
		condition.setCurPage(this.getPageCount());
	}

	private void pageNext() {
		condition.setCurPage(condition.getCurPage() + 1);
	}

	private void pagePrevious() {
		condition.setCurPage(condition.getCurPage() - 1);
	}

	protected void gotoPage() {
		if (condition.isFirst()) {
			this.pageFirst();
		} else if (condition.isLast()) {
			this.pageLast();
		} else if (condition.isPrevious()) {
			this.pagePrevious();
		} else if (condition.isNext()) {
			this.pageNext();
		}
		this.setPageRows();
		this.condition.setPageCount(this.getPageCount());
		this.condition.setPageRowCount(this.getPageRowCount());
	}

	public PageInfo getPageInfo() {
		// TODO Auto-generated method stub
		return pageInfo;
	}

	public void setRowCount(int rowCount) {
		// TODO Auto-generated method stub
		this.condition.setRowCount(rowCount);
		this.gotoPage();
	}

}
